package cn.doitedu.server;

import cn.doitedu.core.DataManagerService;
import cn.doitedu.core.StudentBean;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class DataManagerHttpServer {
    public static void main(String[] args) throws Exception {

        ServerSocket serverSocket = new ServerSocket(8080);
        log.info("web服务器成功注册端口:{}",8080);

        // 构造数据管理核心功能的实例对象
        DataManagerService dataManagerService = new DataManagerService("d:/stu.dat", "d:/meta.obj");


        while(true){
            Socket socket = serverSocket.accept();

            InputStream socketInputStream = socket.getInputStream();
            OutputStream socketOutputStream = socket.getOutputStream();

            // 读取客户端请求中第一行
            BufferedReader br = new BufferedReader(new InputStreamReader(socketInputStream));
            String firstLine = br.readLine();  // GET /query HTTP/1.1
            System.out.println(firstLine);

            String[] firstLineArr = firstLine.split(" ");
            String requestURL = firstLineArr[1];
            // 对url解码
            requestURL = URLDecoder.decode(requestURL,"utf-8");
            log.info("解码后的请求url:{}",requestURL);

            if("/query".equals(requestURL)){

                // 获取html文件
                File htmlFile = new File("htmls/data_query.html");
                // 准备响应头
                String statusLine = "HTTP/1.1 200 OK\r\n";   // 响应行
                String contentType = "Content-Type: text/html; charset=utf-8\r\n";  // 响应头
                String contentLength = "Content-Length: "+ htmlFile.length()+"\r\n\r\n";
                // 发送响应头
                socketOutputStream.write(statusLine.getBytes());
                socketOutputStream.write(contentType.getBytes());
                socketOutputStream.write(contentLength.getBytes());
                // 发送响应体（html文档）
                FileInputStream fileInputStream = new FileInputStream(htmlFile);
                IOUtils.copy(fileInputStream,socketOutputStream);

                socketOutputStream.flush();
                fileInputStream.close();

                socketOutputStream.close();
                socketInputStream.close();
                socket.close();


            }else if(requestURL.startsWith("/api/query")){
                // requestURL => /api/query?condition_name=stu_id&condition_operator=eq&condition_value=3
                // url按照？分两段
                String[] arr = requestURL.split("\\?");
                // 切出参数对，并放入一个hashmap
                HashMap<String, String> parameterMap = new HashMap<>();
                String[] parameterPair = arr[1].split("&");
                for (String pair : parameterPair) {
                    // condition_name=stu_id
                    String[] nameAndValue = pair.split("=");
                    parameterMap.put(nameAndValue[0],nameAndValue[1]);
                }

                String conditionName = parameterMap.getOrDefault("condition_name", "");

                //
                String responseJson = "{\"id\":1}";
                switch (conditionName) {
                    case "stu_id":
                        // 调用系统核心功能的 findById 方法
                        String studentById = dataManagerService.findStudentById(Integer.parseInt(parameterMap.getOrDefault("condition_value", "0")));
                        String[] fields = studentById.split(",");
                        StudentBean studentBean = new StudentBean(Integer.parseInt(fields[0]), fields[1], Integer.parseInt(fields[2]), fields[3], fields[4], fields[5]);

                        responseJson = JSON.toJSONString(studentBean);
                        break;
                    case "stu_name":
                        // 调用系统核心功能的 findByName 方法
                        List<String> studentsByName = dataManagerService.findStudentsByName(parameterMap.getOrDefault("condition_value", "null"));

                        List<StudentBean> beanList = studentsByName.stream().map(s -> {
                            String[] fields2 = s.split(",");
                            return new StudentBean(Integer.parseInt(fields2[0]), fields2[1], Integer.parseInt(fields2[2]), fields2[3], fields2[4], fields2[5]);
                        }).collect(Collectors.toList());


                        responseJson = JSON.toJSONString(beanList);


                        break;
                    case "stu_gender":
                        // 调用系统核心功能的 findByGender 方法


                        break;
                    case "stu_age":
                        // 调用系统核心功能的 findByAge 方法



                        break;
                    case "stu_word":
                        // 调用系统核心功能的 findByWord 方法
                        break;
                }


                int length = responseJson.length();
                System.out.println(responseJson);
                System.out.println(responseJson.getBytes().length);

                // 准备响应头
                String statusLine = "HTTP/1.1 200 OK\r\n";   // 响应行
                String contentType = "Content-Type: application/json; charset=utf-8\r\n";  // 响应头
                String contentLength = "Content-Length: "+ responseJson.getBytes().length +"\r\n\r\n";
                // 发送响应头
                socketOutputStream.write(statusLine.getBytes());
                socketOutputStream.write(contentType.getBytes());
                socketOutputStream.write(contentLength.getBytes());
                // 发送响应体
                socketOutputStream.write(responseJson.getBytes());
                socketOutputStream.flush();

                // 关闭连接
                socketOutputStream.close();
                socketInputStream.close();
                socket.close();



            }



        }


    }

}
